package com.ptswitch.material.service.impl;

import java.io.InputStream;
import java.util.List;

import javax.annotation.Resource;

import org.hxzon.project.Dao;
import org.springframework.stereotype.Service;

import com.ptswitch.material.model.common.HTree;
import com.ptswitch.material.service.HTreeService;
import com.ptswitch.material.util.HTreeResultTransformer;
import com.ptswitch.material.util.SqlReader;

@Service
public class HTreeServiceImpl implements HTreeService {
    @Resource
    protected Dao dao;

    @Override
    public void init() {
        InputStream file = HTreeServiceImpl.class.getResourceAsStream("HTreeService.sql");
        for (String sql : new SqlReader(file).sqls()) {
            dao.sqlExecute(sql);
        }
    }

    @Override
    public List<HTree> findAncestors(String id) {
        String sql = "select * from htree_find_ancs(:id)";
        return dao.sqlList(HTreeResultTransformer.instance, sql, -1, -1,//
                "id", id);
    }

    @Override
    public List<HTree> findDescendants(String pid) {
        String sql = "select * from htree_find_descs(:id) ";
        return dao.sqlList(HTreeResultTransformer.instance, sql, -1, -1,//
                "id", pid);
    }

    @Override
    public List<HTree> findParents(String id) {
        String sql = "select * from htree_htree where id in ("//
                + " select pid from htree_htree where id = :id )";
        return dao.sqlList(HTreeResultTransformer.instance, sql, -1, -1,//
                "id", id);
    }

    @Override
    public List<HTree> findChildren(String pid) {
        String sql = "select * from htree_tree where pid = :pid";
        return dao.sqlList(HTreeResultTransformer.instance, sql, -1, -1,//
                "pid", pid);
    }

    @Override
    public void insert(String id, String pid) {
        String sql = "insert into htree_tree(id,pid) values(:id,:pid)";
        dao.sqlExecute(sql, "id", id, "pid", pid);
    }

    @Override
    public void delete(String id, boolean deleteAllDescs) {
        String sql = deleteAllDescs ? //
        "delete from htree_tree where id in (select id from htree_find_descs(:id)"//
                : "delete from htree_tree where id = :id";
        dao.sqlExecute(sql, "id", id);
    }

    @Override
    public void move(String id, String npid) {
        String sql = "update htree_tree set pid = :pid where id = :id";
        dao.sqlExecute(sql, //
                "id", id, "pid", npid);
    }
}
